from rest_framework import serializers
from .models import Books


class PublishSerializer(serializers.Serializer):
    name = serializers.CharField()
    addr = serializers.CharField()


class AuthorSerializer(serializers.Serializer):
    name = serializers.CharField()
    age = serializers.IntegerField()


'''使用ModelSerializer'''
# class BookSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = Books
#         # fields = '__all__'
#         # 手写可以指定顺序
#         fields = ['id', 'name', 'price', 'publish', 'authors', 'publish_obj', 'authors_list']
#         extra_kwargs = {
#             'name': {'max_length': 8, 'min_length': 3},
#             'publish': {'write_only': True},
#             'authors': {'write_only': True},
#         }
#
#     publish_obj = PublishSerializer(source='publish', read_only=True)
#     authors_list = AuthorSerializer(source='authors', many=True, read_only=True)

'''使用Serializer'''


class BookSerializer(serializers.Serializer):
    id = serializers.IntegerField(required=False)
    book_name = serializers.SerializerMethodField(source='name', read_only=True)

    def get_book_name(self, obj):
        return "《" + obj.name + "》"

    name = serializers.CharField(max_length=8, min_length=3, write_only=True)
    price = serializers.DecimalField(max_digits=5, decimal_places=2)
    publish = serializers.IntegerField(write_only=True)
    authors = serializers.ListField(write_only=True)

    publish_detail = serializers.DictField(read_only=True)
    author_list = serializers.ListField(read_only=True)

    def update(self, instance, validated_data):
        publish_id = validated_data.pop('publish')
        author_list = validated_data.pop('authors')
        for k in validated_data:
            setattr(instance, k, validated_data[k])
        instance.publish_id = publish_id
        instance.authors.set(author_list)
        instance.save()
        # print(validated_data)
        return instance

    def create(self, validated_data):
        publish_id = validated_data.pop('publish')
        author_list = validated_data.pop('authors')
        book = Books.objects.create(**validated_data, publish_id=publish_id)
        book.authors.add(author_list)
        return book
